package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.AgreeRefundReq;
import com.ymatou.iapi.optrade.parameter.req.ApplyRefundReq;
import com.ymatou.iapi.optrade.parameter.req.CancelOrderReq;
import com.ymatou.iapi.optrade.parameter.vo.SalesRefundInfoVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.service.AgreeRefundCall;
import com.ymatou.iapi.optrade.service.CancelOrderCall;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.anlihui.InviteRelation;
import com.ymttest.database.model.anlihui.MemberRelation;
import com.ymttest.database.sqlwapper.anlihui.InviteRelationWrapper;
import com.ymttest.database.sqlwapper.anlihui.MemberRelationWrapper;
import com.ymttest.database.sqlwapper.anlihui.SettlementWrapper;

public class AnlihuiCallService {
	
	private static AgreeRefundReq salesrefundsuccessReq = new AgreeRefundReq();
	private static AgreeRefundCall salesrefundsuccessCall = new AgreeRefundCall();
	
	private static MemberRelationWrapper wrapper = new MemberRelationWrapper();
	private static InviteRelationWrapper inviteRelationWrapper = new InviteRelationWrapper();
	
	/**
	 * 构建安利会会员关系，num为多个人的时候，关系为a<b<c
	 * 
	 * @param level
	 *            会员等级（0：普通买家，1：体验，2：安利，3：海淘 ）
	 * @param num
	 *            会员数量
	 * @param parent_member_id
	 *            上级会员id
	 * @return memberList 返回会员Id列表
	 */
	public static List<Long> buildAnlihuiMemberRelation(int level, int num,
			long parent_member_id) {
		try {

			MemberRelation memberRelation = null;
			long memberId = 0L;
			List<Long> memberList = new ArrayList<Long>();
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.YEAR, 3);

			for (int i = 0; i < num; i++) {

				int userId = new OrderCallService().createNewUser();

				memberRelation = new MemberRelation();
				memberId = Long
						.valueOf(userId);

				memberRelation.setAdd_time(new Date());
				memberRelation.setUpdate_time(new Date());
				memberRelation.setMember_id(memberId);
				memberRelation.setMember_level((byte)level);
				memberRelation.setDeadline(calendar.getTime());
				memberRelation.setParent_id(parent_member_id);
				memberRelation.setBuyvip_order_id(111111L);
				memberRelation.setOpen_type((byte)0);
				memberRelation.setUpgradeable(false);
				
				// 将上一次的hunterId作为下个推手的上级
				parent_member_id = memberId;

				wrapper.insert(memberRelation);

				memberList.add(memberId);
			}

			return memberList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return new ArrayList<Long>();
		}
	}
	
	public static void insertAnlihuiMember(long userId, int level, long parent_member_id) {
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.YEAR, 3);
		
		MemberRelation memberRelation = new MemberRelation();

		memberRelation.setAdd_time(new Date());
		memberRelation.setUpdate_time(new Date());
		memberRelation.setMember_id(userId);
		memberRelation.setMember_level((byte)level);
		memberRelation.setDeadline(calendar.getTime());
		memberRelation.setParent_id(parent_member_id);
		memberRelation.setBuyvip_order_id(111111L);
		memberRelation.setOpen_type((byte)0);
		
		wrapper.insert(memberRelation);
	}
	
	public static void createMember(long orderId, long userId, long inviterId,
			int memberOrderType) throws ClientProtocolException, IOException {

		Logger.comment("开始执行createMember");

		YmatouEasyCall createMemberCall = new YmatouEasyCall("", "POST", "JSON");
		StringBuffer createMemberString = new StringBuffer();

		createMemberString.append("{\"orderId\":" + orderId + "");
		createMemberString
				.append(", \"payTime\":\"2019-10-10 16:41:54\", \"vipDeadline\":\"2022-10-10 16:41:54\"");
		createMemberString.append(", \"userId\":" + userId);
		createMemberString.append(", \"inviterId\":" + inviterId);
		createMemberString.append(", \"memberTypeEnum\":\"" + (memberOrderType == 2 ? "ANLI" : "HAITAO_DAREN")
				+ "\"}");

		createMemberCall
				.setUrl("http://anlimember.iapi.ymatou.com/api/createMember");
		createMemberCall.setData(createMemberString.toString());

		createMemberCall.callService();
	}
	
	/**
	 * 安利结算
	 * 
	 * @param orderId
	 * @param hunterId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void doRebateSettlement() throws ClientProtocolException, IOException {

		Logger.comment("开始执行doRebateSettlement");

		YmatouEasyCall doRebateSettlementCall = new YmatouEasyCall(
				"", "POST", "JSON");
		StringBuffer doRebateSettlementString = new StringBuffer();

		doRebateSettlementString.append("{}");
		
		doRebateSettlementCall
				.setUrl("http://anlisettlement.iapi.ymatou.com/api/doRebateSettlement");
		doRebateSettlementCall
				.setData(doRebateSettlementString.toString());

		doRebateSettlementCall.callService();

		if (doRebateSettlementCall.getReturnData()
				.equalsIgnoreCase("ok"))
			Logger.comment("调用doRebateSettlement成功");
		else
			Logger.comment("调用doRebateSettlement失败");
	}
	
	public static void onOrderPay(long orderType, long buyerId, long sellerId,
			long orderId) throws ClientProtocolException, IOException {

		Logger.comment("开始执行onOrderPay");

		YmatouEasyCall onOrderPayCall = new YmatouEasyCall("", "POST", "JSON");
		StringBuffer onOrderPayString = new StringBuffer();

		onOrderPayString.append("{\"OrderType\":" + orderType);
		onOrderPayString.append(",\"BuyerId\":" + buyerId);
		onOrderPayString
				.append(",\"appId\":\"optrade.iapi.ymatou.com\",\"BusinessType\":2,\"ParamExt\":{}");
		onOrderPayString.append(",\"SellerId\":" + sellerId);
		onOrderPayString.append(",\"OrderId\":" + orderId + "}");

		onOrderPayCall
				.setUrl("http://anlisettlement.iapi.ymatou.com/api/onOrderPay");
		onOrderPayCall.setData(onOrderPayString.toString());

		onOrderPayCall.callService();

		if (onOrderPayCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用onOrderPay成功");
		else
			Logger.comment("调用onOrderPay失败");
	}
	
	public static void onOrderShipped(long buyerId)
			throws ClientProtocolException, IOException {

		Logger.comment("开始执行onOrderShipped");

		YmatouEasyCall onOrderShippedCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer onOrderShippedString = new StringBuffer();

		onOrderShippedString.append("{\"OrderType\":0,\"BuyerId\":" + buyerId);
		onOrderShippedString
				.append(",\"ParamExt\":{\"orderType\":0");
		onOrderShippedString.append(",\"addTime\":\"2019-10-14 20:18:36\"");
		onOrderShippedString.append(",\"payTime\":\"2019-10-14 20:18:41\"");
		onOrderShippedString.append(",\"userId\":" + buyerId);
		onOrderShippedString.append(",\"payableAmount\":105.00}");
		onOrderShippedString.append(",\"SellerId\":24635724,\"OrderId\":1490024647}");

		onOrderShippedCall
				.setUrl("http://anlimember.iapi.ymatou.com/api/onOrderShipped");
		onOrderShippedCall.setData(onOrderShippedString.toString());

		onOrderShippedCall.callService();

		if (onOrderShippedCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用onOrderShipped成功");
		else
			Logger.comment("调用onOrderShipped失败");
	}
	
	public static void onMemberOrderConfirmed(long buyerId)
			throws ClientProtocolException, IOException {

		Logger.comment("开始执行onMemberOrderConfirmed");

		YmatouEasyCall onMemberOrderConfirmedCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer onMemberOrderConfirmedString = new StringBuffer();

		onMemberOrderConfirmedString.append("{\"OrderType\":2,\"BuyerId\":" + buyerId);
		onMemberOrderConfirmedString
				.append(",\"ParamExt\":{\"orderType\":2");
		onMemberOrderConfirmedString.append(",\"addTime\":\"2019-10-14 20:18:36\"");
		onMemberOrderConfirmedString.append(",\"payTime\":\"2019-10-14 20:18:41\"");
		onMemberOrderConfirmedString.append(",\"userId\":" + buyerId);
		onMemberOrderConfirmedString.append(",\"payableAmount\":105.00}");
		onMemberOrderConfirmedString.append(",\"SellerId\":24635724,\"OrderId\":1490024647}");

		onMemberOrderConfirmedCall
				.setUrl("http://anlimember.iapi.ymatou.com/api/onOrderShipped");
		onMemberOrderConfirmedCall.setData(onMemberOrderConfirmedString.toString());

		onMemberOrderConfirmedCall.callService();

		if (onMemberOrderConfirmedCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用onMemberOrderConfirmed成功");
		else
			Logger.comment("调用onMemberOrderConfirmed失败");
	}
	
	/**
	 * 
	 * @param order
	 * @param agreeRefund
	 *            是否同意退款
	 * @param refundNum
	 *            商品退货数量(0代表全部退款)
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void anliOrderRefund(Order order, boolean agreeRefund,
			int refundNum) throws ClientProtocolException, IOException {

		long orderId = order.getOrderId();

		// 申请退款
		ApplyRefundReq applyRefundReq = RefundService.applyRefund(order,
				refundNum);

		if (agreeRefund) {

			salesrefundsuccessReq.setOrderId(orderId);

			int i = 0;

			for (SalesRefundInfoVo salesRefundInfoVo : applyRefundReq
					.getSalesRefundInfoList()) {

				salesrefundsuccessReq.setRefundBillNo(salesRefundInfoVo
						.getRefundBillNo());
				salesrefundsuccessCall.setData(salesrefundsuccessReq);

				Logger.comment(String.format("orderid: %s 第 %s 个商品 退款执行",
						orderId, i + 1));

				salesrefundsuccessCall.callService();

				Logger.verifyEquals("true",
						salesrefundsuccessCall.getString("success"),
						"验证退货退款成功返回");
				i++;
			}
		}
	}
	
	/**
	 * 
	 * @param order
	 * @param agreeRefund
	 *            是否同意退款
	 * @param applyRefundAmount
	 *            退款金额
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void anliOrderRefund(Order order, boolean agreeRefund,
			BigDecimal applyRefundAmount) throws ClientProtocolException, IOException {

		long orderId = order.getOrderId();

		// 申请退款
		ApplyRefundReq applyRefundReq = RefundService.applyRefund(order,
				applyRefundAmount);

		if (agreeRefund) {

			salesrefundsuccessReq.setOrderId(orderId);

			int i = 0;

			for (SalesRefundInfoVo salesRefundInfoVo : applyRefundReq
					.getSalesRefundInfoList()) {

				salesrefundsuccessReq.setRefundBillNo(salesRefundInfoVo
						.getRefundBillNo());
				salesrefundsuccessCall.setData(salesrefundsuccessReq);

				Logger.comment(String.format("orderid: %s 第 %s 个商品 退款执行",
						orderId, i + 1));

				salesrefundsuccessCall.callService();

				Logger.verifyEquals("true",
						salesrefundsuccessCall.getString("success"),
						"验证退货退款成功返回");
				i++;
			}
		}
	}
	
	/**
	 * 
	 * @param order
	 * @param agreeRefund
	 *            是否同意退款
	 * @param applyRefundAmount
	 *            退款金额
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void anliOrderRefund(Order order, boolean agreeRefund, Integer refundNum,
			BigDecimal applyRefundAmount) throws ClientProtocolException, IOException {

		long orderId = order.getOrderId();
		
		// 申请退款
		ApplyRefundReq applyRefundReq = RefundService.applyRefund(order, refundNum,
				applyRefundAmount);

		if (agreeRefund) {

			salesrefundsuccessReq.setOrderId(orderId);

			int i = 0;

			for (SalesRefundInfoVo salesRefundInfoVo : applyRefundReq
					.getSalesRefundInfoList()) {

				salesrefundsuccessReq.setRefundBillNo(salesRefundInfoVo
						.getRefundBillNo());
				salesrefundsuccessCall.setData(salesrefundsuccessReq);

				Logger.comment(String.format("orderid: %s 第 %s 个商品 退款执行",
						orderId, i + 1));

				salesrefundsuccessCall.callService();

				Logger.verifyEquals("true",
						salesrefundsuccessCall.getString("success"),
						"验证退货退款成功返回");
				i++;
			}
		}
	}
	
	public static void anliOrderCancel(long orderId, long userId) {
		
		CancelOrderReq cancelorderReq = new CancelOrderReq();
		CancelOrderCall cancelordercall = new CancelOrderCall();

		cancelorderReq.setCancelReason("自动化测试取消订单");
		cancelorderReq.setCancelType(CancelOrderTypeEnum.CUSTOMER_CANCEL_ORDER);
		cancelorderReq.setOrderId(orderId);
		cancelorderReq.setUserId(userId);

		cancelordercall.setData(false, cancelorderReq);
		try {

			cancelordercall.callService();

		} catch (Exception e) {
			Logger.info(String.format("########取消订单:%s 异常", orderId));
		}
	}
	
	public static boolean isExistSettlement(long orderId) {
		
		SettlementWrapper wrapper = new SettlementWrapper();
		
		return wrapper.selectByOrderId(orderId).size() == 0 ? false : true;
	}
	
	public static void insertInviteRelation(long inviteeId, long inviterId) {
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.YEAR, 3);
		
		InviteRelation inviteRelation = new InviteRelation();

		inviteRelation.setAdd_time(new Date());
		inviteRelation.setUpdate_time(new Date());
		inviteRelation.setInvitee_id(inviteeId);
		inviteRelation.setInviter_id(inviterId);
		inviteRelation.setDeadline(calendar.getTime());
		inviteRelation.setInvite_type((byte)2);
		inviteRelation.setValid(true);
		inviteRelation.setInvitee_first_buyvip_time(new Date());
		
		inviteRelationWrapper.insert(inviteRelation);
	}

	public static void main(String[] args) {
		
		AnlihuiCallService.insertInviteRelation(1470015526, 1470015526);
	}
}
